package com.ssmk.module.my.activity;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.retrofitlibrary.BaseObserBean2;
import com.example.retrofitlibrary.RetrofitClientUtlis;
import com.ssmk.R;
import com.ssmk.adapter.Collection_adapter;
import com.ssmk.base.MVPBaseActivity;
import com.ssmk.bean.CollectionBean;
import com.ssmk.module.home.utils.FontHelper;
import com.ssmk.url.Url;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


public class MyCollectActivity extends MVPBaseActivity implements Collection_adapter.CheckInterface,Collection_adapter.ModifyCountInterface{
    @BindView(R.id.top_iv_back)
    ImageView mTopIvBack;
    @BindView(R.id.top_tv_title)
    TextView mTopTvTitle;
    @BindView(R.id.top_tv_other)
    TextView mTopTvOther;
    @BindView(R.id.collect_arl_btnDelete)//删除
    Button mBtDelete;
    @BindView(R.id.collect_arl_cbSelectAll)//全选
    CheckBox mCbSelectAll;
    @BindView(R.id.collect_recycler)
    RecyclerView collectRecycler;
    @BindView(R.id.collect_arl)
    AutoRelativeLayout mRelativeLayout;
    List<CollectionBean.DataBean.RowsBean>list=new ArrayList<>();
    CollectionBean.DataBean data1=new CollectionBean.DataBean();
    int flag=0;
    private Collection_adapter mAdapter;
    private int totalCount = 0;// 商品总数量

    @OnClick({R.id.top_iv_back,R.id.top_tv_other,R.id.collect_arl_btnDelete,R.id.collect_arl_cbSelectAll})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_iv_back:
                finish();
                break;
            case R.id.top_tv_other:
                if (flag==0){
                    mTopTvOther.setText("完成");
                    mRelativeLayout.setVisibility(View.VISIBLE);
                    data1.setIsEdit(true);

                }else {
                    mTopTvOther.setText("编辑");
                    mRelativeLayout.setVisibility(View.GONE);
                    data1.setIsEdit(false);
                }
                flag = (flag + 1) % 2;//其余得到循环执行上面2个不同的功能
                mAdapter.notifyDataSetChanged();
                break;

            case R.id.collect_arl_cbSelectAll:
                /**
                 * 全选与反选
                 */
                doCheckAll();
                break;

            case R.id.collect_arl_btnDelete:
                AlertDialog alert ;
                if (totalCount == 0) {
                    Toast.makeText(this, "请选择要移除的商品", Toast.LENGTH_LONG).show();
                    return;
                }
                alert = new AlertDialog.Builder(this).create();
                alert.setTitle("操作提示");
                alert.setMessage("您确定要将这些商品从购物车中移除吗？");
                alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        });
                alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                doDelete();
                            }
                        });
                alert.show();
                break;
        }
    }


    @Override
    protected void initview() {
        Resources res = this.getResources();
        String title = res.getString(R.string.shoucnag);
        mTopTvTitle.setText(title);
        mTopTvOther.setText("编辑");
        FontHelper.applyFont(this, mTopTvTitle, 5);
        mAdapter = new Collection_adapter(MyCollectActivity.this, list,data1);
        LinearLayoutManager manager = new LinearLayoutManager(MyCollectActivity.this);
        collectRecycler.setAdapter(mAdapter);
        collectRecycler.setLayoutManager(manager);
        //设置适配器
        mAdapter.setCheckInterface(this);// 关键步骤1,设置复选框接口
        mAdapter.setModifyCountInterface(this);
    }

    @Override
    protected void initdata() {
        SharedPreferences personInfo = getSharedPreferences("personInfo", MODE_PRIVATE);
        String token = personInfo.getString("token", null);
        HashMap<String, String> mapToken = new HashMap<>();
        mapToken.put("token", token);
        HashMap<String, String> map = new HashMap<>();
        map.put("pageNo","1");
        map.put("pageS",10+"");

        RetrofitClientUtlis.getInstance(this, Url.BASEURL2,mapToken)
                .createBaseApi()
                .post2(Url.CollectionList, map, new BaseObserBean2<CollectionBean>(this, CollectionBean.class) {
            @Override
            public void Next(CollectionBean data) {

                data1.setIsEdit(data.getData().isEdit());
                list.addAll(data.getData().getRows());
                mAdapter.notifyDataSetChanged();
            }
        });

    }

    @Override
    protected int layoutRes() {
        return R.layout.activity_my_collect;
    }

    @Override
    public void UpData(Object o) {

    }

    /**
     * 全选
     */
    private void doCheckAll() {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setChoosed(mCbSelectAll.isChecked());
        }
        mAdapter.notifyDataSetChanged();
        calculate();
    }



    /**
     * 删除操作<br>
     * 1.不要边遍历边删除，容易出现数组越界的情况<br>
     * 2.现将要删除的对象放进相应的列表容器中，待遍历完后，以removeAll的方式进行删除
     */
    protected void doDelete() {
        SharedPreferences personInfo = getSharedPreferences("personInfo", MODE_PRIVATE);
        String token = personInfo.getString("token", null);
        final HashMap<String, String> mapToken = new HashMap<>();
        mapToken.put("token", token);
        Map<String,String>map=new HashMap<>();
        StringBuffer sb=new StringBuffer();
        List<CollectionBean.DataBean.RowsBean> lists = new ArrayList<>();// 待删除的组元素列表
        for (int i = 0; i < list.size(); i++) {
            CollectionBean.DataBean.RowsBean rowsBean = list.get(i);
            if (rowsBean.isChoosed()) {
                lists.add(rowsBean);
                sb.append(","+rowsBean.getCollectionId());
            }
        }

        if (sb.length()>0) {
            sb.deleteCharAt(0);
        }
        map.put("collectionIds",sb.toString());
        list.removeAll(lists);
        RetrofitClientUtlis.getInstance(this, Url.BASEURL2,mapToken)
                .createBaseApi()
                .post2(Url.COLLDEDLE, map, new BaseObserBean2<CollectionBean>(this, CollectionBean.class) {
                    @Override
                    public void Next(CollectionBean data) {
                        HashMap<String, String> map = new HashMap<>();
                        map.put("pageNo","1");
                        map.put("pageS",10+"");
                        list.clear();
                        RetrofitClientUtlis.getInstance(MyCollectActivity.this, Url.BASEURL2,mapToken)
                                .createBaseApi()
                                .post2(Url.CollectionList, map, new BaseObserBean2<CollectionBean>(MyCollectActivity.this, CollectionBean.class) {
                                    @Override
                                    public void Next(CollectionBean data) {

                                        data1.setIsEdit(data.getData().isEdit());
                                        list.addAll(data.getData().getRows());
                                        mAdapter.notifyDataSetChanged();
                                    }
                                });
                    }
                });

    }


    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给底部的textView进行数据填充
     */
    private void calculate() {
        totalCount = 0;

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isChoosed()) {
                totalCount++;

            }
        }

    }



    @Override
    public void checkGroup(int position, boolean isChecked) {
            list.get(position).setChoosed(isChecked);
        if (isAllCheck())
            mCbSelectAll .setChecked(true);
        else
            mCbSelectAll.setChecked(false);
        mAdapter.notifyDataSetChanged();
        calculate();
    }
    private boolean isAllCheck() {

        for (CollectionBean.DataBean.RowsBean rowsBean : list) {
            if (!rowsBean.isChoosed())
                return false;

        }

        return true;
    }

    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked) {

    }

    public void onDestroy(){
        super.onDestroy();
        mAdapter=null;
        list.clear();
        totalCount=0;

    }
}
